package com.teng.web.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.teng.dto.JSONResponse;
import com.teng.dto.UserContext;
import com.teng.exception.OAException;
import com.teng.service.UserService;
import com.teng.service.impl.UserServiceImpl;
import com.teng.util.JSONUtil;

@WebServlet("/public-api/user/login")
public class LoginServlet extends HttpServlet {
		public static int ON_LINE_USER=0;
		@Override
		protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			JSONResponse result=new JSONResponse();
			
			try {
				// 1 获取参数(清理和验证参数)
				req.setCharacterEncoding("utf-8");
				String account = req.getParameter("account");
				String password = req.getParameter("password");
				String captha = req.getParameter("captha");
				String loginIp=req.getRemoteHost();
				
				UserService userService=new UserServiceImpl();
				UserContext uc=userService.login(account, password,loginIp);
				
				HttpSession session=req.getSession(false);
				if(session!=null) {
					session.invalidate();
				}
				session=req.getSession(true);
				session.setAttribute("LOGIN", uc);
				session.setAttribute("YANZHENG", true);
				
				result.setCode("ok");
				result.setData(uc);
			}catch(OAException e) {
				result.setCode("0001");
				result.setMessage(e.getMessage());
			}catch(Exception e) {
				result.setCode("error");
				result.setMessage("系统繁忙，请稍候再试!");
				//打印异常信息，用于调试
				e.printStackTrace();
			}finally {
				resp.setContentType("application/json");
				resp.setCharacterEncoding("utf-8");
				Writer out=resp.getWriter();
				out.write(JSONUtil.toJsonString(result));
			}
		}
}
